package com.lyshop.jinding.activitys;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.umeng.analytics.MobclickAgent;
import com.lyshop.jinding.BuildConfig;
import com.lyshop.jinding.R;
import com.lyshop.jinding.base.BaseActivity;
import com.lyshop.jinding.bean.UserInfoBean;
import com.lyshop.jinding.constants.Constant;
import com.lyshop.jinding.eventbus.EventCenter;
import com.lyshop.jinding.eventbus.EventConstants;
import com.lyshop.jinding.net.ActionCallbackListener;
import com.lyshop.jinding.utils.CustomerUtil;
import com.lyshop.jinding.utils.DataUtils;
import com.lyshop.jinding.utils.FastClickUtil;
import com.lyshop.jinding.utils.LogUtil;
import com.lyshop.jinding.utils.RouteUtil;
import com.lyshop.jinding.utils.TimeCount;
import com.lyshop.jinding.utils.ToastUtil;
import com.lyshop.jinding.utils.ToolbarUtils;
import com.lyshop.jinding.utils.auth.BaseUIConfig;
import com.lyshop.jinding.view.LoginRegisterPrivateDialog;
import com.lyshop.jinding.view.MyDialog;
import com.lyshop.jinding.view.MyEditText;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;


public class LoginRegisterActivity extends BaseActivity implements View.OnClickListener,
        RadioGroup.OnCheckedChangeListener, MyEditText.AfterTextWatcher, CompoundButton.OnCheckedChangeListener {
    public static final int TYPE_REGISTER = 0;//注册
    public static final int TYPE_LOGIN = 1;//登录

    private int mType = 1;//默认登录界面

    private View title_bar;
    private RadioGroup rg_title;
    private ImageView iv_left;
    private MyEditText met_mobile;
    private MyEditText met_password;
    private TextView tv_forget_password;
    private TextView tv_pwd_desc;
    private MyEditText et_code;
    private TextView tv_get_code;
    private TextView tv_risk;
    private TextView tv_register_agreement;
    private TextView tv_dangerous_agreement;
    private TextView tv_custom_service;
    private TextView tv_auth_login;
    private TextView tv_problem;
    private Button bt_commit;
    private CheckBox cb_check_agreement;
    private RelativeLayout rl_code;
    private LinearLayout ll_agreement;
    private String mobile = "";
    private TimeCount timeCount;
    private TokenResultListener mTokenResultListener;
    private BaseUIConfig mUIConfig;
    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private Dialog mGiveUpDialog;
    private String registrationID;

    @Override
    protected int setContentView() {
        return R.layout.activity_login_register;
    }

    @Override
    protected void findViews() {
        title_bar = findViewById(R.id.v_title_bar);
        rg_title = findViewById(R.id.rg_title);
        iv_left = findViewById(R.id.iv_left);

        met_mobile = findViewById(R.id.met_mobile);
        met_password = findViewById(R.id.met_pwd);
        tv_forget_password = findViewById(R.id.tv_forget_password);
        tv_pwd_desc = findViewById(R.id.tv_pwd_desc);
        bt_commit = findViewById(R.id.bt_commit);

        met_mobile = findViewById(R.id.met_mobile);
        et_code = findViewById(R.id.et_code);
        tv_problem = findViewById(R.id.tv_problem);
        tv_get_code = findViewById(R.id.tv_get_code);
        tv_risk = findViewById(R.id.tv_risk);
        tv_register_agreement = findViewById(R.id.tv_register_agreement);
        tv_dangerous_agreement = findViewById(R.id.tv_dangerous_agreement);
        cb_check_agreement = findViewById(R.id.cb_check_agreement);
        tv_custom_service = findViewById(R.id.tv_custom_service);
        tv_auth_login = findViewById(R.id.tv_auth_login);

        rl_code = findViewById(R.id.rl_code);
        ll_agreement = findViewById(R.id.ll_agreement);

        ToolbarUtils.setStatusTextColor(true, this);
        ToolbarUtils.setToolbarHeight(this, title_bar);
    }

    @Override
    protected void setListeners() {
        rg_title.setOnCheckedChangeListener(this);

        bt_commit.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);

        tv_get_code.setOnClickListener(this);
        tv_register_agreement.setOnClickListener(this);
        tv_dangerous_agreement.setOnClickListener(this);
        cb_check_agreement.setOnCheckedChangeListener(this);
        tv_risk.setOnClickListener(this);
        tv_custom_service.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        tv_auth_login.setOnClickListener(this);

        met_mobile.addTextWatcher(this);
        met_password.addTextWatcher(this);
        et_code.addTextWatcher(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    public void initData() {
        mType = getIntent().getIntExtra(RouteUtil.BUNDLE_LOGIN_REGISTER_TYPE, TYPE_LOGIN);
        registrationID = JPushInterface.getRegistrationID(mContext);
        LogUtil.d("dangzt", "registerid" + registrationID);

        if (mType == TYPE_REGISTER) {
            rg_title.getChildAt(0).performClick();
        } else {
            rg_title.getChildAt(1).performClick();
        }

        openAuthLoginRegister();
    }

    @Override
    public void onClick(View v) {
        if (FastClickUtil.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_left:
                if (mType == TYPE_LOGIN) {
                    backActivity();
                } else {
                    showGiveUpDialog();
                }
                break;
            case R.id.tv_risk:
                RouteUtil.toWebViewActivity(this, Constant.H5_RISK_DISCLOSURE);
                break;
            case R.id.tv_register_agreement:
                RouteUtil.toWebViewActivity(this, Constant.H5_USER_URL);
                break;
            case R.id.tv_dangerous_agreement:
                RouteUtil.toWebViewActivity(this, Constant.H5_PRIVATE_URL);
                break;
            case R.id.tv_custom_service:
                //打开客服
                CustomerUtil.customerService(this);
                break;
            case R.id.tv_get_code:
                //获取验证码
                getRegisterCode();
                break;
            case R.id.tv_forget_password:
                //找回密码
                RouteUtil.toFindBackPwdActivity(this);
                break;
            case R.id.bt_commit:
                if (!cb_check_agreement.isChecked()){
                    showPrivateConfirmDialog();
                    return;
                }
                loading();
                if (mType == TYPE_REGISTER) {
                    register();
                } else {
                    login();
                }
                break;
            case R.id.bt_leave:
                mGiveUpDialog.dismiss();
                backActivity();
                break;
            case R.id.bt_stay:
                mGiveUpDialog.dismiss();
                break;
            case R.id.tv_auth_login:
                openAuthLoginRegister();
                break;
        }
    }

    private void showPrivateConfirmDialog() {
        LoginRegisterPrivateDialog dialog = new LoginRegisterPrivateDialog(this, new LoginRegisterPrivateDialog.PrivateConfirmListener() {
            @Override
            public void onConfirmListener() {
                cb_check_agreement.setChecked(true);
            }
        });
        dialog.show();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_register:
                rl_code.setVisibility(View.VISIBLE);
                tv_problem.setVisibility(View.VISIBLE);
                tv_custom_service.setVisibility(View.VISIBLE);
                tv_forget_password.setVisibility(View.GONE);
                tv_pwd_desc.setVisibility(View.GONE);
                bt_commit.setText("注册");
                mType = TYPE_REGISTER;
                break;
            case R.id.rb_login:
                rl_code.setVisibility(View.GONE);
                tv_problem.setVisibility(View.GONE);
                tv_custom_service.setVisibility(View.GONE);
                tv_forget_password.setVisibility(View.VISIBLE);
                tv_pwd_desc.setVisibility(View.VISIBLE);
                bt_commit.setText("登录");
                mType = TYPE_LOGIN;
                break;
        }
        afterEnterWatcher();
    }

    @Override
    public void onAfterText(int vId, String text) {
        afterEnterWatcher();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        afterEnterWatcher();
    }

    private void afterEnterWatcher() {
        if (mType == TYPE_REGISTER) {
            String mobile = met_mobile.getText();
            String password = met_password.getText();
            String code = et_code.getText().toString();

//            if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(password) || TextUtils.isEmpty(code) || !cb_check_agreement.isChecked()) {
//                bt_commit.setEnabled(false);
//            } else {
//                bt_commit.setEnabled(true);
//            }
        } else {
            String mobile = met_mobile.getText();
            String password = met_password.getText();

//            if (TextUtils.isEmpty(mobile) || TextUtils.isEmpty(password) || !cb_check_agreement.isChecked()) {
//                bt_commit.setEnabled(false);
//            } else {
//                bt_commit.setEnabled(true);
//            }
        }
    }

    /**
     * 打开一键登录
     */
    private void openAuthLoginRegister() {
        //初始化设置监听
        sdkInit(myApplication.getAuthSecret());
        //设置ui
        mUIConfig = BaseUIConfig.init(Constant.DIALOG_PORT, this, mPhoneNumberAuthHelper);
        //获取token
        oneKeyLogin();
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private void oneKeyLogin() {
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(getApplicationContext(), mTokenResultListener);
        mPhoneNumberAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN);
        mUIConfig.configAuthPage();
        getLoginToken(3000);
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    public void getLoginToken(int timeout) {
        mPhoneNumberAuthHelper.getLoginToken(this, timeout);
    }

    /**
     * 初始化一键登录
     *
     * @param secretInfo
     */
    public void sdkInit(String secretInfo) {
        mTokenResultListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.e("art", "唤起授权页成功：" + s);
                    }

                    if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.e("art", "获取token成功：" + s);
                        mPhoneNumberAuthHelper.hideLoginLoading();
                        //退出页面
                        mPhoneNumberAuthHelper.quitLoginPage();
                        getResultWithToken(tokenRet.getToken());
                        mPhoneNumberAuthHelper.setAuthListener(null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
                Log.e("art", "获取token失败：" + s);

                mPhoneNumberAuthHelper.hideLoginLoading();
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
                        //模拟的是必须登录 否则直接退出app的场景
                        finish();
                    } else {
//                        Toast.makeText(getApplicationContext(), "一键登录失败切换到其他登录方式", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mPhoneNumberAuthHelper.setAuthListener(null);
            }
        };
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenResultListener);
        mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
        mPhoneNumberAuthHelper.setAuthSDKInfo(secretInfo);
    }

    /**
     * 获取注册验证码
     */
    private void getRegisterCode() {
        loading();
        mobile = met_mobile.getText();
        mAppAction.getRegisterCode(mobile, new ActionCallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                cancelLoading();
                timeCount = new TimeCount(tv_get_code, 60000, 1000, "再次获取");
                timeCount.start();
                ToastUtil.showToast(mContext, "验证码发送成功");
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 注册
     */
    private void register() {
        mobile = met_mobile.getText();

        //注册埋点
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("regist_user", mobile);
        MobclickAgent.onEventObject(myApplication, "CLICK_REGIST", userMap);

        mAppAction.register(mobile, et_code.getText().toString(), met_password.getText(), "",
                new ActionCallbackListener<Void>() {
                    @Override
                    public void onSuccess(Void data) {
                        //注册埋点
                        Map<String, Object> userMap = new HashMap<>();
                        userMap.put("regist_user", mobile);
                        MobclickAgent.onEventObject(myApplication, "REGIST_ID", userMap);

                        DataUtils.setRegister(mContext, true);
                        ToastUtil.showToast(mContext, "注册成功");
                        //去登录
                        login();
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        cancelLoading();
                        ToastUtil.showToast(mContext, message);
                    }
                });
    }

    /**
     * 登录
     */
    private void login() {
        DataUtils.clearUserInfo(mContext);
        mobile = met_mobile.getText();
        mAppAction.login(mobile, met_password.getText(), registrationID, new ActionCallbackListener<UserInfoBean>() {
            @Override
            public void onSuccess(final UserInfoBean userInfo) {
                DataUtils.LoginSucess(mContext, userInfo);
                getUserDetail();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 获取用户信息
     */
    private void getUserDetail(){
        mAppAction.getUserDetail(new ActionCallbackListener<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean data) {
                cancelLoading();
                //登录埋点
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("login_user", data.mobile);
                MobclickAgent.onEventObject(myApplication, "LOGIN_ID", userMap);
                //设置用户数据
                DataUtils.setUserInfo(mContext, data);
                if (data.noviceCoupon != null){
                    EventBus.getDefault().postSticky(new EventCenter<UserInfoBean>(EventConstants.EVENTCODE_NOVICE_TICKET));
                }
                backActivity();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    /**
     * 一键登录
     * @param token sdk获取的token
     */
    public void getResultWithToken(final String token) {
        DataUtils.clearUserInfo(mContext);
        loading();
        mAppAction.authOneKey(token, registrationID, new ActionCallbackListener<UserInfoBean>() {
            @Override
            public void onSuccess(UserInfoBean data) {
                DataUtils.LoginSucess(mContext, data);
                getUserDetail();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                cancelLoading();
                ToastUtil.showToast(mContext,message);
            }
        });
    }

    /**
     * 注册挽留弹窗
     */
    private void showGiveUpDialog() {
        if (mGiveUpDialog == null) {
            mGiveUpDialog = new MyDialog(this, true, Gravity.BOTTOM);
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_give_up_register, null);
            Button bt_leave = (Button) view.findViewById(R.id.bt_leave);
            Button bt_stay = (Button) view.findViewById(R.id.bt_stay);
            bt_leave.setOnClickListener(this);
            bt_stay.setOnClickListener(this);
            mGiveUpDialog.setContentView(view);
        }
        mGiveUpDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK && mType == TYPE_REGISTER) {
            showGiveUpDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
